<?php
# 文件名称:table.php
# MetInfo在线反馈系统 
# Copyright (C) 长沙米拓信息技术有限公司 (http://www.metinfo.cn). All rights reserved.
defined( '_SYS' ) or die( 'No direct script access allowed' );
class C_table
{
	/**
	 * 表名
	 *
	 */
	var $_tb_name	= '';
	/**
	 * 表中主键名
	 *
	 */
	var $_tb_key	= '';
	/**
	 * 数据库对象
	 */
	var $_db		= null;
	var	$_errors	= array();
	
	function __construct( $table, $key, &$db )
	{
		$this->_tb_name	= $table;
		$this->_tb_key	= $key;
		$this->_db		=& $db;
	}
	/**
	 * 获取相应表对象的引用
	*/
	function &getInstance( $type, $prefix = 'C_table', $config = array() )
	{
		$false = false;
		$type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type);
		$tableClass = $prefix.ucfirst($type);
		if (!class_exists( $tableClass ))
		{
		
			if($path = dirname(__FILE__).DS.'table'.DS.strtolower($type).'.php')
			{
				require_once $path;
				if (!class_exists( $tableClass ))
				{
					return $false;
				}
			}
			else
			{
				return $false;
			}
		}
		//确认有数据库对象存在
		if (array_key_exists('dbo', $config))  {
			$db =& $config['dbo'];
		} else {
			$db = C_loader::getDBO();
		}
		$instance = new $tableClass($db);		
		return $instance;
	}
	function &getDBO()
	{
		if($this->_db == null)
		{
			$this->_db = C_loader::getDBO();
		}
		return $this->_db;
	}
	function setDBO(&$db)
	{
		$this->_db =& $db;
	}
	/**
	 * 获取内部私有表名
	 */
	function getTableName()
	{
		return $this->_tb_name;
	}
	/**
	 * 获取内部私有主键变量名
	 */
	function getKeyName()
	{
		return $this->_tb_key;
	}
	/**
	 * 重置默认属性值，不重置主键
	 */
	function reset()
	{
		$k = $this->_tb_key;
		foreach ($this->getProperties() as $name => $value)
		{
			if($name != $k)
			{
				$this->$name	= $value;
			}
		}
	}
	function getProperties( $public = true )
	{
		$vars  = get_object_vars($this);
        if($public)
		{
			foreach ($vars as $key => $value)
			{
				if ('_' == substr($key, 0, 1)) {
					unset($vars[$key]);
				}
			}
		}
        return $vars;
	}
	/**
	 * 绑定数据
	 */
	function bind( $from, $ignore=array() )
	{
		$fromArray	= is_array( $from );
		$fromObject	= is_object( $from );
		if (!$fromArray && !$fromObject)
		{
			$this->setError( get_class( $this ).'::bind failed. Invalid from argument' );
			return false;
		}
		if (!is_array( $ignore )) {
			$ignore = explode( ' ', $ignore );
		}
		foreach ($this->getProperties() as $k => $v)
		{
			if (!in_array( $k, $ignore ))
			{
				if ($fromArray && isset( $from[$k] )) {
					$this->$k = $from[$k];
				} else if ($fromObject && isset( $from->$k )) {
					$this->$k = $from->$k;
				}
			}
		}
		return true;
	}
	/**
	 * 加载记录并绑定
	 */
	function load( $oid=null )
	{
		$k = $this->_tb_key;
		if ($oid !== null) {
			$this->$k = $oid;
		}
		$oid = $this->$k;
		if ($oid === null) {
			return false;
		}
		$this->reset();
		$db =& $this->getDBO();
		$query = 'SELECT *'
		. ' FROM '.$this->_tb_name
		. ' WHERE '.$this->_tb_key.' = '.$db->Quote($oid);
		$db->setQuery( $query );
		if ($result = $db->loadAssoc( )) {
			return $this->bind($result);
		}
		else
		{
			$this->setError( $db->getErrorMsg() );
			return false;
		}
	}
	/**
	 *
	 * 虚函数
	 *
	 */
	function check()
	{
		return true;
	}
	/**
	 * 如果为0就插入新纪录，否则更新记录。
	 *
	 */
	function store( $updateNulls=false, $opt=true)
	{
		$k = $this->_tb_key;
		$key =  $this->$k;
		
		if ($key)
		{
			$ret = $this->_db->updateObject( $this->_tb_name, $this, $this->_tb_key, $updateNulls );
		}
		else
		{
			$ret = $this->_db->insertObject( $this->_tb_name, $this, $this->_tb_key );
			
		}
		if( !$ret )
		{
			$this->setError( strtolower(get_class( $this ))."::store failed<br />" . $this->_db->getErrorMsg() );
			return false;
		}
		else
		{
			return true;
		}
	}
	/**
	 * 检查依赖关系
	 */
	function canDelete( $oid=null, $joins=null )
	{
		$k = $this->_tb_key;
		if ($oid) {
			$this->$k = intval( $oid );
		}
		if (is_array( $joins ))
		{
			$select = "$k";
			$join = "";
			foreach( $joins as $table )
			{
				$select .= ', COUNT(DISTINCT '.$table['idfield'].') AS '.$table['idfield'];
				$join .= ' LEFT JOIN '.$table['name'].' ON '.$table['joinfield'].' = '.$k;
			}
			$query = 'SELECT '. $select
			. ' FROM '. $this->_tb_name
			. $join
			. ' WHERE '. $k .' = '. $this->_db->Quote($this->$k)
			. ' GROUP BY '. $k
			;
			$this->_db->setQuery( $query );
			if (!$obj = $this->_db->loadObject())
			{
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
			$msg = array();
			$i = 0;
			foreach( $joins as $table )
			{
				$k = $table['idfield'] . $i;
				if ($obj->$k)
				{
					$msg[] = JText::_( $table['label'] );
				}
				$i++;
			}
			if (count( $msg ))
			{
				$this->setError("noDeleteRecord" . ": " . implode( ', ', $msg ));
				return false;
			}
			else
			{
				return true;
			}
		}
		return true;
	}
	function delete( $oid=null )
	{
		$k = $this->_tb_key;
		if ($oid) {
			$this->$k = intval( $oid );
		}
		$query = 'DELETE FROM '.$this->_db->nameQuote( $this->_tb_name ).
				' WHERE '.$this->_tb_key.' = '. $this->_db->Quote($this->$k);
		$this->_db->setQuery( $query );
		if ($this->_db->query())
		{
			return true;
		}
		else
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
	}
	/**
	 * 保存流程
	 */
	function save( $source, $order_filter='', $ignore='' )
	{
		if (!$this->bind( $source, $ignore )) {
			return false;
		}
		if (!$this->check()) {
			return false;
		}
		if (!$this->store()) {
			return false;
		}
		if (!$this->checkin()) {
			return false;
		}
		if ($order_filter)
		{
			$filter_value = $this->$order_filter;
			$this->reorder( $order_filter ? $this->_db->nameQuote( $order_filter ).' = '.$this->_db->Quote( $filter_value ) : '' );
		}
		$this->setError('');
		return true;
	}

	/**
	 * 导出为xml数据
	 */
	function toXML( $mapKeysToText=false )
	{
		$xml = '<record table="' . $this->_tb_name . '"';
		if ($mapKeysToText)
		{
			$xml .= ' mapkeystotext="true"';
		}
		$xml .= '>';
		foreach (get_object_vars( $this ) as $k => $v)
		{
			if (is_array($v) or is_object($v) or $v === NULL)
			{
				continue;
			}
			if ($k[0] == '_')
			{ // 内部变量
				continue;
			}
			$xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
		}
		$xml .= '</record>';
		return $xml;
	}
	function setError($error)
	{
		array_push($this->_errors, $error);
	}
	
	function get($property, $default=null)
	{
		if(isset($this->$property)) {
			return $this->$property;
		}
		return $default;
	}
	function set( $property, $value = null )
	{
		$previous = isset($this->$property) ? $this->$property : null;
		$this->$property = $value;
		return $previous;
	}
}
# 本程序是一个开源系统,使用时请你仔细阅读使用协议,商业用途请自觉购买商业授权.
# Copyright (C) 长沙米拓信息技术有限公司 (http://www.metinfo.cn). All rights reserved.
?>
